package cn.niu;

import cn.niu.controller.DemoController;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by niusibao on 2017/8/1 0001.
 */
@Service
public class SocketHandler extends BinaryWebSocketHandler {
    Logger logger = Logger.getLogger(SocketHandler.class);
    Map<String, String> sessionMap = new HashMap<>();

    List<WebSocketSession> list = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        Map<String, String> map = new HashMap<>();
        String query = session.getUri().getQuery();

        if (query != null && !query.equals("")) {
            String[] queries = query.split("&");

            for (String q : queries) {
                String[] params = q.split("=");
                if (params.length > 1) {
                    map.put(params[0], params[1]);
                }
            }
        }

        String name = map.get("name");
        if (name != null && !name.equals("")) {
            sessionMap.put(session.getId(), name);
            DemoController.getLive(name);
        } else {
            list.add(session);
        }
        logger.info("name:" + name + ",session:" + session.getId());
        TextMessage textMessage = new TextMessage(session.getId());
        session.sendMessage(textMessage);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        list.remove(session);
        logger.info("session:" + session.getId() + ",close:" + status);
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws IOException {
        byte[] bytes = message.getPayload().array();
        Live live = DemoController.getLive(sessionMap.get(session.getId()));
        live.putStream(bytes);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println(message.getPayload());
    }
}
